package com.itentbase.match.common.utils;


import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


/**
 * 判断日期对应的星期是否正确
 */
public class WeekUtils {

    public static String isWeekAndDate(String dateString, String weekDay) {

        //将星期几转换为英文表达
        String weekDayEng = null;
        if (weekDay.equals("周一")) {
            weekDayEng = "MONDAY";
        } else if (weekDay.equals("周二")) {
            weekDayEng = "TUESDAY";
        } else if (weekDay.equals("周三")) {
            weekDayEng = "WEDNESDAY";
        } else if (weekDay.equals("周四")){
            weekDayEng = "THURSDAY";
        } else if (weekDay.equals("周五")){
            weekDayEng = "FRIDAY";
        } else if (weekDay.equals("周六")){
            weekDayEng = "SATURDAY";
        } else {
            weekDayEng = "SUNDAY";
        }
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 将字符串解析为 LocalDate 类型的时间
        LocalDate date = LocalDate.parse(dateString, formatter);
        DayOfWeek week = date.getDayOfWeek(); //判断是星期几

        if (week.equals(weekDayEng)){
            LocalDate previousDay  = date.minusDays(1); //将日期减一天
            return previousDay.toString();
        }
        return date.toString();
    }

    /**
     * 将中文星期天字符串转换为DayOfWeek枚举值
     *
     * @param weekdayString 中文星期天字符串
     * @return 对应的DayOfWeek枚举值
     */
    public static DayOfWeek convertToDayOfWeek(String weekdayString) {
        Map<String, DayOfWeek> weekdayMap = new HashMap<>();
        weekdayMap.put("周一", DayOfWeek.MONDAY);
        weekdayMap.put("周二", DayOfWeek.TUESDAY);
        weekdayMap.put("周三", DayOfWeek.WEDNESDAY);
        weekdayMap.put("周四", DayOfWeek.THURSDAY);
        weekdayMap.put("周五", DayOfWeek.FRIDAY);
        weekdayMap.put("周六", DayOfWeek.SATURDAY);
        weekdayMap.put("周日", DayOfWeek.SUNDAY);

        return weekdayMap.getOrDefault(weekdayString, null);
    }

    /**
     * 根据当前日期和目标星期几，返回目标星期几的日期（如果当前日期的星期和目标的星期相同则返回当前日期）
     *
     * @param currentDate 当前日期
     * @param targetDayOfWeek 目标星期几
     * @return 下一个星期的日期
     */
    public static LocalDate findNextWeekday(LocalDate currentDate, DayOfWeek targetDayOfWeek) {
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek();
        // 计算目标星期几与当前星期几的差距
        int daysUntilTarget = (targetDayOfWeek.getValue() - currentDayOfWeek.getValue() + 7) % 7;
        if (daysUntilTarget == 0) {
            return currentDate;
        }
        return currentDate.plusDays(daysUntilTarget);
    }

}
